// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.Data.SqlClient;

namespace SnapObjects.Data.SqlServer
{
    internal class SqlServerAdoDbCommand : AdoDbCommand
    {
        public SqlServerAdoDbCommand(
            [NotNull] string sqlText,
            IEnumerable<IAdoDbParameter> parameters,
            bool addExceptionToTransaction,
            CommandType commandType = CommandType.Text)
            : base(sqlText, parameters, addExceptionToTransaction, commandType)
        {
        }

        public override void ExecuteParseOnly(DataContext dataContext)
        {
            try
            {
                base.ExecuteParseOnly(dataContext);
            }
            catch
            {
                var command = this.CreateCommand(dataContext);

                command.CommandText = "SET NOEXEC OFF";

                command.ExecuteNonQuery();

                throw;
            }
        }

        public override Task ExecuteParseOnlyAsync(
            DataContext dataContext, CancellationToken cancellationToken = default)
        {
            try
            {
                return base.ExecuteParseOnlyAsync(dataContext, cancellationToken);
            }
            catch
            {
                var command = this.CreateCommand(dataContext);

                command.CommandText = "SET NOEXEC OFF";

                command.ExecuteNonQueryAsync(cancellationToken);

                throw;
            }
        }

        protected override string BuildNoExecCommandText(DataContext context, string commandText)
        {
            return $@"
                SET NOEXEC ON;
                {commandText};
                SET NOEXEC OFF;";
        }

        protected override int GetSqlDbCode(Exception innerException)
        {
            if (innerException is SqlException ex)
            {
                return ex.Number;
            }

            return -1;
        }
    }
}
